const config = require('./config')
const Koa = require('koa')
const parserBody = require('koa-bodyparser')
const catchError = require('./middlewares/error-handle')
const cors = require('koa2-cors')
const logger = require('./core/logger')
const app = new Koa()

const { install } = require('./core/init')
// 跨域处理
app.use(
  cors({
    origin: function (ctx) {
      return '*' // 允许来自所有域名请求
      // return ctx.header.origin;// 当*无法使用时，使用这句,同样允许所有跨域
      // return 'http://localhost:8080'; //单个跨域请求
      // 允许多个跨域
      var allowCors = ['http://localhost:3000', 'http://localhost:8081', 'http://localhost:5173']
      return allowCors.indexOf(ctx.header.origin) > -1 ? ctx.header.origin : ''
    },
    exposeHeaders: ['WWW-Authenticate', 'Server-Authorization'],
    maxAge: 5,
    credentials: true,
    allowMethods: ['GET', 'POST', 'DELETE'],
    allowHeaders: ['Content-Type', 'Authorization', 'Accept'],
  })
)
// 解析参数
app.use(parserBody())
// 全局异常处理
app.use(catchError)
// 初始化
install(app)

const HOST = '127.0.0.1'
app.listen(config.port, () => {
  console.log(`服务运行在: ${HOST}:${config.port}`)
})

app.on('error', (err, ctx) => {
  console.log('🚀 ~ koa 报错', ctx)
  logger.error(err + ctx)
  ctx.body = {
    msg: '系统服务错误',
    code: 500,
    data: {},
    request: {
      methods: ctx.request.method,
      url: ctx.request.url,
    },
  }
  ctx.status = 500
})
